<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    title="角色权限配置"
    width="40%"
    destroyOnClose
    @ok="handleSubmit"
    showFooter
  >
    <BasicTree
      ref="treeRef"
      multiple
      checkable
      :treeData="treeData"
      :replaceFields="{ title: 'label', key: 'id' }"
      :checkedKeys="checkedKeys"
      :expandedKeys="expandedKeys"
      :checkStrictly="true"
      toolbar
      title="所拥有的的权限"
      @expand="onExpand"
      @check="onCheck"
    />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getMenuTree } from '/@/api/system/system';
  import { queryTreeListForRole, queryRolePermission, saveRolePermission } from './role.api';

  const treeData = ref<TreeItem[]>([]);
  const allTreeKeys = ref([]);
  const checkedKeys = ref();
  const defaultCheckedKeys = ref([]);
  const expandedKeys = ref([]);
  const autoExpandParent = ref(true);
  const roleId = ref('');
  const treeRef = ref(null);
  /**
   * 数据
   */
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await reset();
    setDrawerProps({ confirmLoading: false });
    roleId.value = data.roleId;
    // 初始化数据
    treeData.value = await getMenuTree();
    const roleResult = await queryTreeListForRole(roleId.value);
    allTreeKeys.value = roleResult;
    const permResult = await queryRolePermission({ roleId: unref(roleId) });
    checkedKeys.value = [...permResult];
    defaultCheckedKeys.value = [...permResult];
    expandedKeys.value = unref(allTreeKeys);
  });
  /**
   * 展开
   */
  function onExpand(expandedKeys) {
    expandedKeys.value = expandedKeys;
    autoExpandParent.value = false;
  }
  /**
   * 选择
   */
  function onCheck(o) {
    checkedKeys.value = o.checked ? o.checked : o;
  }
  /**
   * 数据重置
   */
  function reset() {
    treeData.value = [];
    allTreeKeys.value = [];
    checkedKeys.value = [];
    defaultCheckedKeys.value = [];
    expandedKeys.value = [];
    autoExpandParent.value = true;
    roleId.value = '';
  }
  /**
   * 获取tree实例
   */
  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  /**
   * 提交
   */
  async function handleSubmit() {
    let params = {
      roleId: unref(roleId),
      menuIds: unref(getTree().getCheckedKeys()),
      lastPermissionIds: unref(defaultCheckedKeys).join(','),
    };
    await saveRolePermission(params);
    closeDrawer();
  }
</script>

<style scoped></style>
